package com.xxc.exam.exhandler

import com.xxc.common.enums.ResultCode
import com.xxc.common.exceptions.BusinessException
import com.xxc.response.result.PlatformResult
import com.xxc.validate.info.ParameterInvalidItem
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.validation.FieldError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
import org.thymeleaf.expression.Lists
import javax.servlet.http.HttpServletRequest

/**
 * @author xxc、
 */
@RestController
@ControllerAdvice
class GlobalExceptionHandler {

    private val logger = LoggerFactory.getLogger(GlobalExceptionHandler::class.java)

    @ExceptionHandler(Exception::class)
    fun handleException(e:Exception):PlatformResult<*>{
        e.printStackTrace()
        return PlatformResult<Any>(ResultCode.SYSTEM_INNER_ERROR)
    }

    @ExceptionHandler(BusinessException::class)
    fun handleBusinessException(businessException: BusinessException):PlatformResult<*>{
        businessException.printStackTrace()
        return PlatformResult(businessException.code,businessException.message,businessException.data)
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException::class)
    fun handleMethodArgumentNotValidException(e:MethodArgumentNotValidException, request:HttpServletRequest):PlatformResult<*> {
        logger.info("handleMethodArgumentNotValidException start, uri:{}, caused by: ", request.getRequestURI(), e)
        val parameterInvalidItemList = ArrayList<ParameterInvalidItem>()

        val fieldErrorList = e.getBindingResult().getFieldErrors()
        for ( fieldError in fieldErrorList) {
            val parameterInvalidItem = ParameterInvalidItem()
            parameterInvalidItem.fieldName = fieldError.getField()
            parameterInvalidItem.message = fieldError.getDefaultMessage()
            parameterInvalidItemList.add(parameterInvalidItem)
        }

        return PlatformResult.failure(ResultCode.PARAM_IS_INVALID, parameterInvalidItemList)
    }
}
